package cn.chencq.collection.map;

public class MyHashMap {

	private MyEntry[] entryArr;

	private int size;

	public MyHashMap() {
		this(10);
	}

	public MyHashMap(int initialCapacity) {
		if (initialCapacity < 0) {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		entryArr = new MyEntry[initialCapacity];
	}

	private void ensureCapacity() {
		if (size == entryArr.length) {
			MyEntry[] newArray = new MyEntry[size * 2 + 1];
			System.arraycopy(entryArr, 0, newArray, 0, entryArr.length);
			entryArr = newArray;
		}
	}

	public int size() {
		return this.size;
	}

	public void put(Object key, Object value) {
		MyEntry e = new MyEntry(key, value);
		ensureCapacity();
		int index = -1;
		for (int i = 0; i < size; i++) {
			if (entryArr[i].getKey().equals(key)) {
				index = i;
				break;
			}
		}

		if (index >= 0) { 
			entryArr[index] = e;
		} else {
			entryArr[size++] = e;
		}
	}

	public Object get(Object key) {
		for (int i = 0; i < size; i++) {
			if (entryArr[i].getKey().equals(key)) {
				return entryArr[i].getValue();
			}
		}
		return null;
	}

	public void remove(Object key) {
		int index = -1;
		for (int i = 0; i < size; i++) {
			if (entryArr[i].getKey().equals(key)) {
				index = i;
				break;
			}
		}
		if (index >= 0) {
			System.arraycopy(entryArr, index + 1, entryArr, index, size - index - 1);
			entryArr[size--] = null;
		}
	}

	private boolean containsKey(Object key) {
		for (int i = 0; i < size; i++) {
			if (entryArr[i].getKey().equals(key)) {
				return true;
			}
		}
		return false;
	}

	private boolean containsValue(Object value) {
		for (int i = 0; i < size; i++) {
			if (entryArr[i].getValue().equals(value)) {
				return true;
			}
		}
		return false;
	}

	private boolean isEmpty() {
		return size == 0;
	}

	public static void main(String[] args) {
		MyHashMap m = new MyHashMap(3);
		m.put("aa", 11);
		m.put("bb", 22);
		m.put("cc", 33);
		m.put("dd", 44);

		System.out.println(m.size());
		System.out.println(m.get("aa"));
		m.remove("bb");
		System.out.println(m.size());

		m.put("dd", 55);
		System.out.println(m.get("dd"));
	}

}

class MyEntry {
	private Object key;
	private Object value;

	public MyEntry(Object key, Object value) {
		super();
		this.key = key;
		this.value = value;
	}

	public Object getKey() {
		return key;
	}

	public void setKey(Object key) {
		this.key = key;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}
}
